package com.atung.parking.config.permission;

import com.atung.parking.config.exception.PermissionValidException;
import com.atung.parking.config.result.ApiResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(PermissionValidException.class)
    public ResponseEntity<ApiResult> handlePermissionValidException(PermissionValidException ex, WebRequest request) {
        return ResponseEntity.status(HttpStatus.OK).body(ApiResult.noPermissionValid());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<ApiResult> handleUsernameNotFoundException(PermissionValidException ex, WebRequest request) {
        return ResponseEntity.status(HttpStatus.OK).body(ApiResult.noAuth());
    }

    @Override
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String,String>message=new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            message.put(fieldName,errorMessage);
        });
        return ResponseEntity.status(HttpStatus.OK).body(ApiResult.fail(message.toString()));
    }
}
